const express = require('express');
const router = express.Router();
const db = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { phone, password } = req.body;

    // 验证手机号和密码是否提供
    if (!phone || !password) {
      return res.status(400).json({ message: '请提供手机号和密码' });
    }

    // 查询用户
    const [users] = await db.query('SELECT * FROM users WHERE phone = ?', [phone]);
    const user = users[0];

    // 验证用户是否存在
    if (!user) {
      return res.status(401).json({ message: '用户不存在' });
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({ message: '密码错误' });
    }

    // 生成 JWT token
    const token = jwt.sign(
      { userId: user.id, phone: user.phone },
      'your-secret-key',  // 在实际生产环境中，应该使用环境变量存储密钥
      { expiresIn: '24h' }
    );

    // 返回用户信息和token
    res.json({
      token,
      userInfo: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { phone, password, nickname } = req.body;

    // 验证必要字段
    if (!phone || !password) {
      return res.status(400).json({ message: '请提供手机号和密码' });
    }

    // 检查手机号是否已注册
    const [existingUsers] = await db.query('SELECT id FROM users WHERE phone = ?', [phone]);
    if (existingUsers.length > 0) {
      return res.status(400).json({ message: '该手机号已注册' });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 插入新用户
    const [result] = await db.query(
      'INSERT INTO users (phone, password, nickname) VALUES (?, ?, ?)',
      [phone, hashedPassword, nickname || null]
    );

    res.status(201).json({
      message: '注册成功',
      userId: result.insertId
    });

  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 用户登录
router.post('/login', async (req, res) => {
    try {
        const { phone, password } = req.body;
        
        // 查询用户
        const [users] = await db.query(
            'SELECT * FROM users WHERE phone = ? AND password = ?',
            [phone, password]
        );

        if (users.length === 0) {
            return res.status(401).json({ error: '手机号或密码错误' });
        }

        const user = users[0];
        
        // 生成 token
        const token = jwt.sign(
            { userId: user.id },
            'your-secret-key',
            { expiresIn: '7d' }
        );

        res.json({
            token,
            userInfo: {
                id: user.id,
                nickname: user.nickname,
                phone: user.phone,
                avatarUrl: user.avatar_url
            }
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 用户注册
router.post('/register', async (req, res) => {
    try {
        const { phone, password, nickname } = req.body;
        
        // 检查手机号是否已存在
        const [existing] = await db.query(
            'SELECT id FROM users WHERE phone = ?',
            [phone]
        );

        if (existing.length > 0) {
            return res.status(400).json({ error: '该手机号已注册' });
        }

        // 创建新用户
        const [result] = await db.query(
            'INSERT INTO users (phone, password, nickname) VALUES (?, ?, ?)',
            [phone, password, nickname]
        );

        res.json({
            message: '注册成功',
            userId: result.insertId
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;